const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = mongoose.Schema({
  // 账号
  account: {
    type: String,
    unique: true,
    required: true,
  },
  // 昵称
  name: {
    type: String,
    default: "暂无昵称",
  },
  // 密码
  password: {
    type: String,
    required: true,
  },
  // 组别
  group: {
    type: String,
    // required: true,
  },
  // 角色：调查员、管理员、审核员
  role: {
    type: String,
    enum: ["user", "admin", "auditor"],
    default: "user",
  },
  reportNumber: {
    type: Number,
    default: 0,
  },
});

userSchema.pre("save", function (next) {
  const user = this;
  //当密码有更改(或是新密码)产生密码hash
  if (!user.isModified("password")) {
    return next();
  }
  //产生一个salt
  bcrypt.genSalt(10, (err, salt) => {
    if (err) return next(err);
    //结合salt产生新的hash
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) return next(err);
      //使用hash覆盖明文密码
      user.password = hash;
      next();
    });
  });
});

//验证
userSchema.methods.comparePassword = function (candidatePassword) {
  const user = this;
  return new Promise((resolve, reject) => {
    bcrypt.compare(candidatePassword, user.password, (err, isMatch) => {
      if (err) {
        return reject(err);
      }
      if (!isMatch) {
        return reject(false);
      }
      resolve(true);
    });
  });
};

const User = mongoose.model("User", userSchema);
module.exports = User;
